package com.kehutong.wwin.event;

import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;

import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.util.ReqBody;
import org.coraframework.mvc.util.RequestUtils;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.Objects;

import com.kehutong.common.DoveClient;
import com.kehutong.common.interceptor.IgornLog;
import com.kehutong.common.webchat.XmlUtil;
import com.kehutong.wwin.event.entity.Event;
import com.kehutong.wwin.event.util.DecEncryptUtil;
import com.kehutong.wwin.event.util.EventQueue;
import com.kehutong.wwin.event.util.EventStatus;
import com.kehutong.wwin.event.util.EventWorker;

@IgornLog
@MvcAction
@ReqMapping("/kht-bin/wwin/event")
public class EventService {

	static Logger logger = LoggerFactory.getLogger(EventService.class);
	
	@Inject
	private EventQueue eventQueue;
	@Inject
	private JdbcSession jdbcSession;
	@Inject
	private DoveClient doveClient;
	@Inject
	private DecEncryptUtil decEncryptUtil;
	

	@ReqMapping(value="/employee/${corpId}", reqBody=ReqBody.NONE)
	public Object employeeCallBack(String corpId, HttpServletRequest req) throws Exception {
		logger.info("内建事件回调employeeCallBack......................................................begin");
		final String text = RequestUtils.readText(req);
		logger.debug("config:{}", text);
		if (!isXml(text)) {
			String content = URLDecoder.decode(req.getParameter("echostr"), "UTF-8");
			String result = decEncryptUtil.decEncrypt(corpId, "1", content, req);
			return Result.text(result);
		}
		
		return doHandle(corpId, text, req, "1");
	}

	@ReqMapping(value="/contact/${corpId}", reqBody=ReqBody.NONE)
	public Object contactCallBack(String corpId, HttpServletRequest req) throws Exception {
		logger.info("内建事件回调contactCallBack......................................................begin");
		final String text = RequestUtils.readText(req);
		logger.debug("config:{}", text);
		if (!isXml(text)) {
			String content = URLDecoder.decode(req.getParameter("echostr"), "UTF-8");
			String result = decEncryptUtil.decEncrypt(corpId, "2", content, req);
			return Result.text(result);
		}
		
		return doHandle(corpId, text, req, "2");
	}

	private Object doHandle(String corpId, String text, HttpServletRequest req, String type) throws Exception {
		logger.info("doHandle......................................................begin");
		JSONObject json = XmlUtil.xml2JSON(text);
		String content = URLDecoder.decode(json.getString("Encrypt"), "UTF-8");
		
		Event event = Pool.newInstance(Event.class);
		String result = decEncryptUtil.decEncrypt(corpId,type, content, req, config->{
			event.setKhtid(config.getKhtId());
		});
		json = XmlUtil.xml2JSON(result);
	
		event.setCropid(json.getString("ToUserName"));
		event.setMsgType(json.getString("MsgType"));
		event.setEvent(json.getString("Event"));
		event.setChangeType(json.getString("ChangeType"));;
		event.setNonce(req.getParameter("nonce"));
		event.setMsg_signature(req.getParameter("msg_signature"));
		event.setTimestamp(req.getParameter("timestamp"));
		event.setContent(json.toJSONString());
		event.setStatus(EventStatus.RECIVED);
		jdbcSession.insert(event);
		
		
		eventQueue.addWork(new EventWorker(event));
		logger.info("doHandle......................................................end");
		return Result.text("success");
	}
	
	/**
	 * 是否xml格式
	 * @param text
	 * @return
	 */
	private boolean isXml(String text) {
		if (Objects.isEmpty(text)) {
			return false;
		}

		for (int i = 0, len = text.length(); i < len; i ++) {
			if (text.charAt(i) == ' ') {
				continue;
			} else if (text.charAt(i) == '<') {
				return true;
			} else {
				return false;
			}
		}

		return false;
	}

}
